
    var fs=require('fs');
    var dbpath='db.json';
    //读取文件所欲数据
    exports.filesall=function(collback){
    fs.readFile(dbpath,'utf-8',function(err,data){
    if(err){
        collback(err)
    }
        collback(null,JSON.parse(data))
    })
    }
    //增加数据
    exports.filesadd=function(newdata,collback){
        fs.readFile(dbpath,'utf-8',function(err,data){
    if(err){
        collback("500 Internal Server Error ")
    }
    var students=JSON.parse(data).students
            if(students.length==0){
                newdata.id=0
            }else {
                newdata.id=students[students.length-1].id+1
            }
    students.push(newdata);
    students=JSON.stringify({students})
            fs.writeFile(dbpath,students,function(err){
                if(err){
                    collback(err)
                }
                collback(null)
            })
        })
    }
    //修改文件数据
    exports.filesalter=function(id,collback){
        console.log(exports)
        fs.readFile(dbpath,'utf-8',function(err,data){
            if(err){
                collback("500 Internal Server Error ")
            }
            var students=JSON.parse(data).students
            var ret=students.find(function(item){
               return item.id===id
            })
            collback(null,ret)
        })
    }
    //更新数据
    exports.updata=function(newdata,collback){
        newdata.id=parseInt( newdata.id)
        newdata.age=parseInt( newdata.age)
        newdata.height=parseInt( newdata.height)
        fs.readFile(dbpath,'utf-8',function(err,data){
            if(err){
                collback("500 Internal Server Error ")
            }
            var students=JSON.parse(data).students
            var stuindex=students.findIndex(function(item){
                return item.id=== newdata.id
            })
            var student= students[stuindex]
            for(var key in student){
                student[key]=newdata[key]
            }
            students=JSON.stringify({students})
            fs.writeFile(dbpath,students,function(err){
                if(err){
                    collback(err)
                }
                collback(null)
            })
        })
    }
    //删除数据
    exports.filesdelete=function(id,collback){
        console.log(id)
        fs.readFile(dbpath,'utf-8',function(err,data){
            if(err){
               return  collback(err)
            }
            var students=JSON.parse(data).students
            var stuindex=students.findIndex(function(item){
                return item.id=== parseInt(id)
            })
           students.splice(stuindex,1)
console.log(students)
            students=JSON.stringify({students})
            fs.writeFile(dbpath,students,function(err){
                if(err){
                  return   collback(err)
                }
                collback(null)
            })
        })
    }
